//
//  MULLoginManager.m
//  UniLoginSDK
//
//  Created by Song Xiaofeng on 13-11-27.
//  Copyright (c) 2013年 Mafengwo Inc. All rights reserved.
//

#import "MULLoginManager.h"
#import "STHTTPRequest.h"
#import "MULXAuthInfo.h"
#import "MULXAuthHttpRequest.h"
#import "STKeychain.h"
#import "MULH5UserInfoBridge.h"
#import "MULPasswordEncryptUtil.h"

#define KeychainDefaultUserName @"defaultUser"
#define KeychainRealUserName @"realUser"


NSString *kLoginURL = @"http://www.e-oid.org.cn/oid/interfaceapp/login_app";
NSString *kRegisterURL = @"http://www.e-oid.org.cn/oid/interfaceapp/register_app";
//NSString *k3rdPartLoginURL = @"https://www.youyuwei.com/api/user/login3rd";

static NSString *kKeychain_Service_Token = nil;

NSString *__mul_consumerKey = nil;
NSString *__mul_consumerSecret = nil;
NSString *__mul_defaultToken = nil;
NSString *__mul_defaultTokenSecret = nil;

NSString *__mul_userToken = nil;
NSString *__mul_userTokenSecret = nil;

@interface MULLoginManager()
{
    MULXAuthHttpRequest *_currentRequest;
    NSString *_uid;
    
    MULXAuthHttpRequest *_defaultTokenRequest;
}

@property (nonatomic, copy)LoginFinished operationFinishedBlock;
@property (nonatomic, copy)DidStartBind startBindBlock;
@end

LoginFinished __stubFinishBlock = ^(BOOL success, NSDictionary *baseInfo, NSDictionary *extraInfo, NSError *error)
{
};

@implementation MULLoginManager

+ (MULMBProgressHUD*)showTextTips:(NSString *)textTips inView:(UIView*)parentView;
{
    if (parentView && [textTips length] > 0)
    {
        MULMBProgressHUD *hud = [MULMBProgressHUD showHUDAddedTo:parentView animated:YES];
        
        // Configure for text only and offset down
        hud.mode = MULMBProgressHUDModeText;
        hud.labelText = textTips;
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        
        [hud hide:YES afterDelay:2];
        return hud;
    }
    
    return nil;
}

+ (void)load
{
    kKeychain_Service_Token = [NSString stringWithFormat:@"%@.%@", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleIdentifierKey], @"keychain_token"];
}

+ (MULLoginManager*)sharedInstance;
{
    static MULLoginManager *_sharedInstance = nil;
	if (_sharedInstance == nil)
	{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _sharedInstance = [[MULLoginManager alloc] init];
			
        });
	}
	
	return _sharedInstance;
}

/**
 *  set XAuth consumerkey which identify the unique
 *
 *  @param consumerKey
 *  @param consumerSecret
 *
 *  @return MULLoginManager class, so you could write contiuous setter methods of class-methods
 */
+ (Class)startWithXAuthConsumerKey:(NSString*)consumerKey andConsumerSecret:(NSString*)consumerSecret;
{
    __mul_consumerKey = [consumerKey copy];
    __mul_consumerSecret = [consumerSecret copy];
    
    // start
    [MULLoginManager sharedInstance];
    
    return [self class];
}

/**
 *  set XAuth default token and token secret, which used for non-login reuqests
 *
 *  @param xauthToken
 *  @param tokenSecret
 *
 *  @return
 */
+ (Class)setXAuthDefaultToken:(NSString *)xauthToken andSecret:(NSString*)tokenSecret;
{
    // We should make sure that MULLoginManager instance has been created,
    // which trigger loading saved defaultToken firstly. If not saved we will use
    // these parameters which passed by this function.
    [MULLoginManager sharedInstance];
    
    if ([__mul_defaultToken length] == 0 || [__mul_defaultTokenSecret length] == 0)
    {
        __mul_defaultToken = [xauthToken copy];
        __mul_defaultTokenSecret = [tokenSecret copy];
    }
    
    return [self class];
}

+ (void)getSignatureToken:(NSString**)token andSecret:(NSString**)secret;
{
    if ([__mul_userToken length] > 0 && [__mul_userTokenSecret length] > 0)
    {
        *token = [__mul_userToken copy];
        *secret = [__mul_userTokenSecret copy];
    }
    else
    {
        *token = [__mul_defaultToken copy];
        *secret = [__mul_defaultTokenSecret copy];
    }
}


+ (void)getConsumerKey:(NSString**)consumerKey andConsumerSecret:(NSString**)consumerSecret;
{
    *consumerKey = [__mul_consumerKey copy];
    *consumerSecret = [__mul_consumerSecret copy];
}

static NSString *const tokenSecretSplitor = @"|&|";

- (NSString *)tokenSecretSerialStr:(NSString*)uid secret:(NSString*)secret andToken:(NSString*)token
{
    return [NSString stringWithFormat:@"%@%@%@%@%@", uid, tokenSecretSplitor, @"0", tokenSecretSplitor, @"0"];
}

- (void)getUid:(NSString**)uid Token:(NSString**)token secret:(NSString**)secret fromTokenSecretSerial:(NSString*)serial;
{
    NSArray *serialArray = [serial componentsSeparatedByString:tokenSecretSplitor];
    if (serialArray && serialArray.count >=3)
    {
        *uid = [serialArray objectAtIndex:0];
        *secret = [serialArray objectAtIndex:1];
        *token = [serialArray objectAtIndex:2];
    }
}

- (void)clearRealUserKeychain
{
    [STKeychain deleteItemForUsername:KeychainRealUserName andServiceName:kKeychain_Service_Token error:nil];
}

/**
 *  sotre default token-secret pair in system keychain
 *
 *  @param xauthToken
 *  @param tokenSecret
 *
 *  @return success or not
 */
- (BOOL)setAccessToken:(NSString*)xauthToken andSecret:(NSString *)tokenSecret forUserId:(NSString*)uid;
{
    BOOL success = NO;
    if ([uid length] > 0)
    {
        if ([xauthToken length] > 0 && [tokenSecret length] > 0)
        {
            NSString *keychainUsername = @"defautUser";
            
            if ([@"0" isEqualToString:uid])
            {
                __mul_defaultToken = xauthToken;
                __mul_defaultTokenSecret = tokenSecret;
                keychainUsername = KeychainDefaultUserName;
            }
            else
            {
                __mul_userToken = xauthToken;
                __mul_userTokenSecret = tokenSecret;
                _uid = uid;
                
                keychainUsername = KeychainRealUserName;
            }
            
            NSError *error = nil;
            
            NSString *keychainSecretSerial = [self tokenSecretSerialStr:uid secret:tokenSecret andToken:xauthToken];
            
            success = [STKeychain storeUsername:keychainUsername andPassword:keychainSecretSerial forServiceName:kKeychain_Service_Token updateExisting:YES error:&error];
            
        }
        else
        {
            NSString *keychainUsername = @"defautUser";
            if ([@"0" isEqualToString:uid])
            {
                //临时token不应该重置为nil
                //                self.defaultToken = nil;
                //                self.defaultTokenSecret = nil;
                success = YES;
                keychainUsername = KeychainDefaultUserName;
            }
            else
            {
                __mul_userToken = nil;
                __mul_userTokenSecret = nil;
                
                keychainUsername = KeychainRealUserName;
            }
            
            success = [STKeychain deleteItemForUsername:keychainUsername andServiceName:kKeychain_Service_Token error:nil];
        }
    }
    
    return success;
}

- (void)getCookie
{
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    NSDictionary *cookies = [defaults objectForKey:@"cookie"];
//    if(!cookies && [self hasLogin]) {
//        
//    }
}

- (BOOL)setCookie:(NSDictionary*)cookies;
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:cookies forKey:@"cookie"];
    [defaults synchronize];
    
    [cookies enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSString *value = obj;
        NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
        [cookieProperties setObject:key forKey:NSHTTPCookieName];
        [cookieProperties setObject:[value urlEncode] forKey:NSHTTPCookieValue];
        [cookieProperties setObject:@".youyuwei.com" forKey:NSHTTPCookieDomain];
        [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
        [cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
        [cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:365*5*24*3600] forKey:NSHTTPCookieExpires];
        
        NSHTTPCookie *cookieuser = [NSHTTPCookie cookieWithProperties:cookieProperties];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser];
        
    }];
    
    return true;
}

- (BOOL)updateAccessToken:(NSString*)token andSecret:(NSString*)secret forUid:(NSString*)uid;
{
    if (!self.hasLogin)
    {
        return [self setAccessToken:@"0" andSecret:@"0" forUserId:uid];
    }
    return NO;
}

+ (MULXAuthInfo*)xauthInfo;
{
    MULXAuthInfo *xauthInfo = [[MULXAuthInfo alloc] init];
    xauthInfo.consumerKey = __mul_consumerKey;
    xauthInfo.consumerSecret = __mul_consumerSecret;
    xauthInfo.defaultXAuthToken = __mul_defaultToken;
    xauthInfo.defaultTokenSecret = __mul_defaultTokenSecret;
    
    xauthInfo.userXAuthToken = __mul_userToken;
    xauthInfo.userTokenSecret = __mul_userTokenSecret;
    
    return xauthInfo;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        [self _initialize];
    }
    return self;
}

/**
 *  check app is firstly install or not. We will check a specific
 *  file's existing.
 *
 *  @return YES if firstly install
 */
- (BOOL)checkFirstInstallApp
{
    @synchronized(NSFileManager.class)
    {
        NSFileManager *fileManager = [ NSFileManager defaultManager];
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
        
        NSString *checkFile = [libraryPath stringByAppendingPathComponent:@"app_has_installed"];
        if ([fileManager fileExistsAtPath:checkFile isDirectory:NO])
        {
            return NO;
        }
        else
        {// firstly install, and we will create a empty file to mark app has benn installed
            [fileManager createFileAtPath:checkFile contents:nil attributes:nil];
            return YES;
        }
    }
}

- (void)_initialize
{
    // load default and user token info from keychain
    // About storing them to keychain see @selector(setAccessToken:andSecret:forUserId:)
    NSString *tokenSerial = nil;
    NSString *uid = nil;
    NSString *token = nil;
    NSString *tokenSecret = nil;
    
    NSError *error = nil;
    
    if ([self checkFirstInstallApp])
    {
        [self clearRealUserKeychain];
    }
    else
    {
        // get real user info
        tokenSerial = [STKeychain getPasswordForUsername:KeychainRealUserName andServiceName:kKeychain_Service_Token error:&error];
        if (!error)
        {
            [self getUid:&uid Token:&token secret:&tokenSecret fromTokenSecretSerial:tokenSerial];
            
            _uid = [uid copy];
            __mul_userToken = [token copy];
            __mul_userTokenSecret = [tokenSecret copy];
        }
    }
    
    // get default user info
    tokenSerial = [STKeychain getPasswordForUsername:KeychainDefaultUserName andServiceName:kKeychain_Service_Token error:&error];
    if (!error)
    {
        [self getUid:&uid Token:&token secret:&tokenSecret fromTokenSecretSerial:tokenSerial];
        if ([@"0" isEqualToString:uid])
        {
            __mul_defaultToken = [token copy];
            __mul_defaultTokenSecret = [tokenSecret copy];
        }
    }
    
    
    [self refreshDefaultToken];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActivie:) name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)appDidBecomeActivie:(NSNotification*)notification
{
    [self getCookie];
}

- (BOOL)hasLogin
{
//    return [__mul_userToken length] > 0 && [__mul_userTokenSecret length] > 0 && [_uid length] > 0;
    return [_uid length] > 0;
}

#pragma mark -
- (BOOL)isRequestSending
{
    return _operationFinishedBlock != nil;
}

- (void)_requestDidFinished:(NSData*)responseData jsonData:(NSDictionary*)parsedJson errorOrNil:(NSError*)error forOperationType:(MULLoginOperationType)optType
{
    if (!error)
    {
        if (parsedJson)
        {
            int status = 0;
//            if([parsedJson hasValueForKey:@"rc"]) {
//                status = [parsedJson intValueForKey:@"rc"];
//            }
            if (status == 0)
            {
                NSDictionary *data = [parsedJson valueForKey:@"data"];
                if (![data isKindOfClass:[NSDictionary class]])
                {
                    data = nil;
                }
                NSDictionary *userExtraInfo = [data valueForKey:@"extinfo"];
                
                
//                NSString *accessToken = [data valueForKey:@"oauth_token"];
//                NSString *tokenSecret = [data valueForKey:@"oauth_token_secret"];
                NSString *uid = nil;
                id uidValue = [data valueForKey:@"id"];
                if ([uidValue isKindOfClass:[NSNumber class]])
                {
                    uid = [uidValue stringValue];
                }
                else if ([uidValue isKindOfClass:[NSString class]])
                {
                    uid = uidValue;
                }

//                if ([uid length] > 0 && [accessToken length] > 0 && [tokenSecret length] > 0)

                if ([uid length] > 0)
                {
                    // uid为0的账户是默认账户，用于未登录时，故当uid != @"0"时视为有效的用户登录
                    if (![@"0" isEqualToString:uid])
                    {
//                        [self setAccessToken:accessToken andSecret:tokenSecret forUserId:uid];
                       
                        if (self.operationFinishedBlock)
                        {
                            self.operationFinishedBlock(YES, data, userExtraInfo, error);
                            self.operationFinishedBlock = nil;
                        }
                        
                        [[NSNotificationCenter defaultCenter] postNotificationName:kMULUserDidLogin object:nil userInfo:parsedJson];
                        
                    }
                    else
                    {
//                        [self setAccessToken:accessToken andSecret:tokenSecret forUserId:uid];
                    }
                    
                    //写入cookie
//                    NSDictionary *cookies = [data objectForKey:@"cookie"];
//                    [self setCookie:cookies];
                    
                }
                else
                {// error
                    // create NSError with error infomation
                    error = [NSError errorWithDomain:kMULLoginErrorDomain code:-1 userInfo:@{kMULLoginErrorMessage: @"request result is not validated!"}];
                }
            }
            else
            {// error
                NSString *errorInfo = [parsedJson valueForKey:@"rm"];
                error = [NSError errorWithDomain:kMULLoginErrorDomain code:status userInfo:@{kMULLoginErrorMessage: errorInfo}];
            }
        }
        else
        {// error
            error = [NSError errorWithDomain:kMULLoginErrorDomain code:-1 userInfo:@{kMULLoginErrorMessage: @"parse data error!"}];
        }
        
    }
    
    if (error)
    {
        NSLog(@"%@", error);
        if (self.operationFinishedBlock)
        {
            self.operationFinishedBlock(NO, nil, nil, error);
            self.operationFinishedBlock = nil;
        }
    }
    
    if (optType == kLoginOpt_DefaultLogin)
    {
        _defaultTokenRequest = nil;
    }
    else
    {
        _currentRequest = nil;
    }
}

//- (void)_thirdPartCheckingDidFinished:(NSData*)responseData jsonData:(NSDictionary*)parsedJson errorOrNil:(NSError*)error venderInfo:(MULThirdPartInfo*)venderInfo
//{
//    if (!error)
//    {
//        if (parsedJson)
//        {
//            
//            int status = [[parsedJson valueForKey:@"status"] intValue];
//            if (status == 1)
//            {
//                NSDictionary *data = [parsedJson valueForKey:@"data"];
//                if (![data isKindOfClass:[NSDictionary class]])
//                {
//                    data = nil;
//                }
//                NSDictionary *userExtraInfo = [data valueForKey:@"extinfo"];
//                
//                id bangValue = [userExtraInfo valueForKey:@"bang"];
//                if (bangValue)
//                {
//                    int bang = -1;
//                    if ([bangValue respondsToSelector:@selector(intValue)])
//                    {
//                        bang = [bangValue intValue];
//                    }
//
//                    if (bang == 0)
//                    {// 为绑定马蜂窝帐号
//                        [self startBindThirdPartAccount:venderInfo];
//                    }
//                    else if (bang == 1)
//                    {// 已经绑定了马蜂窝帐号
//                        self.startBindBlock = nil;
//                        [self _requestDidFinished:responseData jsonData:parsedJson errorOrNil:error forOperationType:kLoginOpt_3rdLogin];
//                    }
//                    else
//                    {// error
//                        error = [NSError errorWithDomain:kMULLoginErrorDomain code:-1 userInfo:@{kMULLoginErrorMessage:@"Checking result: Illegal 'bang' vaule"}];
//                    }
//                }
//                else
//                {
//                    error = [NSError errorWithDomain:kMULLoginErrorDomain code:-1 userInfo:@{kMULLoginErrorMessage:@"Checking result: But has no 'bang' vaule"}];
//                }
//            }
//            else
//            {// error
//                NSString *errorInfo = [parsedJson valueForKey:@"info"];
//                error = [NSError errorWithDomain:kMULLoginErrorDomain code:-1 userInfo:@{kMULLoginErrorMessage: errorInfo}];
//            }
//        }
//        else
//        {// error
//            error = [NSError errorWithDomain:kMULLoginErrorDomain code:-1 userInfo:@{kMULLoginErrorMessage: @"parse data error!"}];
//        }
//    }
//    
//    if (error)
//    {
//        NSLog(@"%@", error);
//        if (self.operationFinishedBlock)
//        {
//            self.operationFinishedBlock(NO, nil, nil, error);
//            self.operationFinishedBlock = nil;
//        }
//    }
//
//}

- (void)refreshDefaultToken;
{
//    _defaultTokenRequest = [MULXAuthHttpRequest requestWithURLString:kLoginURL];
//    _defaultTokenRequest.HTTPMethod = kHttpPOST;
//    _defaultTokenRequest.requestParamerts = [NSMutableDictionary dictionaryWithDictionary:@{@"x_auth_username":@"",
//                                                                               @"x_auth_password":@""}];
//    
//    __weak id wself = self;
//    _defaultTokenRequest.xauthRequestDidCompleteBlock = ^(NSData* responseData, NSDictionary *parsedJson, NSError* error) {
//        __strong id sself = wself;
//        if (sself)
//        {
//            [sself _requestDidFinished:responseData jsonData:parsedJson errorOrNil:error forOperationType:kLoginOpt_DefaultLogin];
//        }
//    };
//    
//    [_defaultTokenRequest startAsynchronous];
}

- (BOOL)loginWithMFWAccount:(NSString*)account
                   password:(NSString*)password
              finishedBlock:(LoginFinished)finiihedBlock;
{
    return [self loginWithMFWAccount:account password:password openUDID:nil finishedBlock:finiihedBlock];
}

- (BOOL)loginWithMFWAccount:(NSString*)account
                   password:(NSString*)password
                   openUDID:(NSString*)openUDID
              finishedBlock:(LoginFinished)finishedBlock;
{
    if ([account length] == 0 || [password length] == 0)
    {
        return NO;
    }
    
    [self cancelLoginOrRegistration];
    
    if (finishedBlock)
    {
        self.operationFinishedBlock = finishedBlock;
    }
    else
    {
        self.operationFinishedBlock = __stubFinishBlock;
    }
    
  //  NSString *encryptedPwd = [MULPasswordEncryptUtil encryptPassword:password];
    if (!openUDID)
    {
        openUDID = @"";
    }
    _currentRequest = [MULXAuthHttpRequest requestWithURLString:kLoginURL];
    _currentRequest.HTTPMethod = kHttpGET;
    
    _currentRequest.requestParamerts = [NSMutableDictionary dictionaryWithDictionary:@{@"account":account,
                                                                                       @"password":password,
                                                                                       }];
    
    __weak id wself = self;
    _currentRequest.xauthRequestDidCompleteBlock = ^(NSData* responseData, NSDictionary *parsedJson, NSError* error) {
        __strong id sself = wself;
        if (sself)
        {
            [sself _requestDidFinished:responseData jsonData:parsedJson errorOrNil:error forOperationType:kLoginOpt_Login];
        }
    };
    
    [_currentRequest startAsynchronous];
    
    return YES;
}

//- (BOOL)loginWith3rdUid:(NSString*)userid
//                   type:(NSString*)type
//                   name:(NSString*)name
//                 header:(NSString*)header
//               location:(NSString*)location
//                 gender:(NSString*)gender
//                unionId:(NSString*)unionId
//          finishedBlock:(LoginFinished)finishedBlock
//{
//    if ([userid length] == 0 || [type length] == 0)
//    {
//        return NO;
//    }
//    
//    [self cancelLoginOrRegistration];
//    
//    if (finishedBlock)
//    {
//        self.operationFinishedBlock = finishedBlock;
//    }
//    else
//    {
//        self.operationFinishedBlock = __stubFinishBlock;
//    }
//    
//    _currentRequest = [MULXAuthHttpRequest requestWithURLString:k3rdPartLoginURL];
//    _currentRequest.HTTPMethod = kHttpGET;
//    if ([type isEqualToString:@"3"]){
//        _currentRequest.requestParamerts = [NSMutableDictionary dictionaryWithDictionary:@{@"userid":userid,
//                                                                                           @"type":type,
//                                                                                           @"name":name,
//                                                                                           @"header":header,
//                                                                                           @"location":location,
//                                                                                           @"gender":gender,
//                                                                                           @"unionid":unionId
//                                                                                           }];
//    }else{
//        _currentRequest.requestParamerts = [NSMutableDictionary dictionaryWithDictionary:@{@"userid":userid,
//                                                                                           @"type":type,
//                                                                                           @"name":name,
//                                                                                           @"header":header,
//                                                                                           @"location":location,
//                                                                                           @"gender":gender,
//                                                                                           }];
//    }
//   
//    __weak id wself = self;
//    _currentRequest.xauthRequestDidCompleteBlock = ^(NSData* responseData, NSDictionary *parsedJson, NSError* error) {
//        __strong id sself = wself;
//        if (sself)
//        {
//            [sself _requestDidFinished:responseData jsonData:parsedJson errorOrNil:error forOperationType:kLoginOpt_Login];
//        }
//    };
//    
//    [_currentRequest startAsynchronous];
//    
//    return YES;
//}

- (BOOL)registerWithMFWAccount:(NSString*)account
                      password:(NSString*)password
                      nickName:(NSString*)nickName
                 finishedBlock:(LoginFinished)finishedBlock;
{
    return [self registerWithMFWAccount:account password:password nickName:nickName openUDID:nil email:nil finishedBlock:finishedBlock];
}

- (BOOL)registerWithMFWAccount:(NSString*)account
                      password:(NSString*)password
                      nickName:(NSString*)nickName
                      openUDID:(NSString*)openUDID
                         email:(NSString*)email
                 finishedBlock:(LoginFinished)finishedBlock;
{

    if ([account length] == 0 || [password length] == 0 )
    {
        return NO;
    }
    
    [self cancelLoginOrRegistration];
    
    if (finishedBlock)
    {
        self.operationFinishedBlock = finishedBlock;
    }
    else
    {
        self.operationFinishedBlock = __stubFinishBlock;
    }
    
    if (!openUDID)
    {
        openUDID = @"";
    }


    
    _currentRequest = [MULXAuthHttpRequest requestWithURLString:kRegisterURL];
    _currentRequest.HTTPMethod = kHttpGET;
    _currentRequest.requestParamerts = [NSMutableDictionary dictionaryWithDictionary:@{@"account":account,
                                                                                       @"password":password,
                                                                                       @"email":email
                                                                                       } ];
    
    __weak id wself = self;

    _currentRequest.xauthRequestDidCompleteBlock = ^(NSData* responseData, NSDictionary *parsedJson, NSError* error) {
        __strong id sself = wself;
        if (sself)
        {
            [sself _requestDidFinished:responseData jsonData:parsedJson errorOrNil:error forOperationType:kLoginOpt_Reg];
        }
    };
    
    [_currentRequest startAsynchronous];
    
    return YES;
}


//- (BOOL)loginWith3rdPartAppKey:(NSString*)appkey
//             clientAccessToken:(NSString*)clientAccessToken
//                     sourceUID:(NSString*)sourceUID
//                   expiredDate:(NSDate*)expiredDate
//                 thirdPartType:(MULLoginThirdPartType)type
//                      nickName:(NSString*)nickName
//                       logoUrl:(NSString*)logoUrl
//                startBindBlock:(DidStartBind)startBindBlock
//                 finishedBlock:(LoginFinished)finishedBlock;
//{
//        return [self loginWith3rdPartAppKey:appkey
//                           clientAccessToken:clientAccessToken
//                                wechatUniqid:nil sourceUID:sourceUID
//                                 expiredDate:expiredDate
//                               thirdPartType:type
//                                    nickName:nickName
//                                     logoUrl:logoUrl
//                                   openUDID:nil
//                              startBindBlock:startBindBlock
//                               finishedBlock:finishedBlock];
//}

//- (BOOL)loginWith3rdPartAppKey:(NSString*)appkey
//             clientAccessToken:(NSString*)clientAccessToken
//                  wechatUniqid:(NSString*)uniqid
//                     sourceUID:(NSString*)sourceUID
//                   expiredDate:(NSDate*)expiredDate
//                 thirdPartType:(MULLoginThirdPartType)type
//                      nickName:(NSString*)nickName
//                       logoUrl:(NSString*)logoUrl
//                      openUDID:(NSString*)openUDID
//                startBindBlock:(DidStartBind)startBindBlock
//                 finishedBlock:(LoginFinished)finishedBlock;
//{
//
//    [self cancelLoginOrRegistration];
//    
//    if (finishedBlock)
//    {
//        self.operationFinishedBlock = finishedBlock;
//    }
//    else
//    {
//        self.operationFinishedBlock = __stubFinishBlock;
//    }
//    
//    self.startBindBlock = startBindBlock;
//    
//    MULThirdPartInfo *venderInfo = MULThirdPartInfo.new;
//    venderInfo.appKey = appkey;
//    venderInfo.token = clientAccessToken;
//    venderInfo.sourceUID = sourceUID;
//    venderInfo.expiredDate = expiredDate;
//    venderInfo.sourceType = type;
//    venderInfo.uniqId = uniqid;
//    
//    venderInfo.userName = nickName;
//    venderInfo.logoUrl = logoUrl;
//    
//    if (!openUDID)
//    {
//        openUDID = @"";
//    }
//    
//    NSAssert(venderInfo.appKey
//             && venderInfo.token
//             && venderInfo.sourceUID
//             && venderInfo.expiredDate
//             && venderInfo.sourceStr, @"Third part authorized info NOT correct!");
//    _currentRequest = [MULXAuthHttpRequest requestWithURLString:k3rdPartLoginURL];
//    _currentRequest.HTTPMethod = kHttpGET;
//    NSMutableDictionary *reqParams = [NSMutableDictionary dictionaryWithDictionary:@{@"t":@"vCheck",
//                                                                               @"origin":venderInfo.sourceStr,
//                                                                               @"appkey":venderInfo.appKey,
//                                                                               @"appuid":venderInfo.sourceUID,
//                                                                               @"token":venderInfo.token,
//                                                                               @"open_udid":openUDID,
//                                                                               @"expires_in":[NSString stringWithFormat:@"%.0f", [venderInfo.expiredDate timeIntervalSince1970]]}];
//    
//    if (venderInfo.uniqId)
//    {
//        [reqParams setValue:venderInfo.uniqId forKey:@"uniqid"];
//    }
//
//    _currentRequest.requestParamerts = reqParams;
//    
//    __weak id wself = self;
//    _currentRequest.xauthRequestDidCompleteBlock = ^(NSData* responseData, NSDictionary *parsedJson, NSError* error) {
//        __strong id sself = wself;
//        if (sself)
//        {
//            [sself _thirdPartCheckingDidFinished:responseData jsonData:parsedJson errorOrNil:error venderInfo:venderInfo];
//        }
//    };
//    
//    [_currentRequest startAsynchronous];
//    
//    return YES;
//}

- (void)logout;
{
    if ([self hasLogin])
    {
        // delete user token and secret
        [self setAccessToken:nil andSecret:nil forUserId:_uid];
        __mul_userToken = nil;
        __mul_userTokenSecret = nil;
        
        [MULH5UserInfoBridge cleanAllCookies];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kMULUserDidLogout object:nil];
    }

}

- (void)cancelLoginOrRegistration;
{
    if (_currentRequest)
    {
        [_currentRequest cancel];
    }
}

//- (void)startBindThirdPartAccount:(MULThirdPartInfo*)venderInfo
//{
//    if (self.startBindBlock)
//    {
//        self.startBindBlock();
//        self.startBindBlock = nil;
//    }
//    
//    __weak id wself = self;
//    MULBindAccountController *bindAccountController = [[MULBindAccountController alloc] initWithThirdPartInfo:venderInfo];
//    [bindAccountController startBindAccountWithResultHandler:^(NSData *responseData, NSDictionary *parsedJson) {
//        id sself = wself;
//        if (sself)
//        {
//            [sself _requestDidFinished:responseData jsonData:parsedJson errorOrNil:nil forOperationType:kLoginOpt_3rdLogin];
//        }
//    }];
//}
#ifdef DEBUG
- (NSString*)debugInfo
{
    NSMutableString *str = [[NSMutableString alloc] init];
    NSError *error = nil;
    // get default user info
    NSString *tokenSerial = [STKeychain getPasswordForUsername:KeychainDefaultUserName andServiceName:kKeychain_Service_Token error:&error];
    [str appendFormat:@"default user token: %@\n", tokenSerial];
    tokenSerial = [STKeychain getPasswordForUsername:KeychainRealUserName andServiceName:kKeychain_Service_Token error:&error];
    [str appendFormat:@"real user token: %@\n", tokenSerial];
    
    return [NSString stringWithString:str];
}
#endif
@end
